<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>修改密码</title>
		<link rel="stylesheet" href="layui/css/layui.css">
		<script src="layui/layui.js" type="text/javascript"></script>
	</head>
	<body>
		<form class="layui-form" action="">
		  <div class="layui-form-item">
		    <label class="layui-form-label">原始密码</label>
		    <div class="layui-input-block">
		      <input type="password" name="oldPass" lay-verify="oldPass" autocomplete="off" placeholder="请输入原始密码" class="layui-input">
		    </div>
		  </div>
		  <div class="layui-form-item">
		    <label class="layui-form-label">新密码</label>
		    <div class="layui-input-block">
		      <input type="password" name="password" lay-verify="password" autocomplete="off" placeholder="请输入新密码" class="layui-input">
		    </div>
		  </div>
		  <div class="layui-form-item">
		    <label class="layui-form-label">确认密码</label>
		    <div class="layui-input-block">
		      <input type="password" name="password2" lay-verify="password2" autocomplete="off" placeholder="请再次输入新密码" class="layui-input">
		    </div>
		  </div>
		  <div class="layui-form-item">
		    <div class="layui-input-block">
		      <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1">立即提交</button>
		      <button type="reset" class="layui-btn layui-btn-primary">重置</button>
		    </div>
		  </div>
		</form>
		<script>
			let user = localStorage.getItem('loginUser');
			user = JSON.parse(user);
			layui.use(['form', 'layedit'], function(){
			  var form = layui.form
			  ,layer = layui.layer
			  ,layedit = layui.layedit
			  ,$ = layui.$;
			  
			  $.ajaxSetup({
			  	xhrFields: {
			  		withCredentials: true
			  	}
			  });
			  //创建一个编辑器
			  var editIndex = layedit.build('LAY_demo_editor');
			 
			  //自定义验证规则
			  form.verify({
				oldPass: function(value){
				  if(value.length < 1){
					return '标题至少得1个字符啊';
				  }else{
					  if(user.password !== value){
						  return '旧密码不正确';
					  }
				  }
				}
				,password: [
				  /^[\S]{6,12}$/
				  ,'新密码必须6到12位，且不能出现空格'
				]
				,password2: function(value){
				  if($("input[name='password']").val() !== value){
					  return '两次密码不一致';
				  }
				}
			  });
			  
			  //监听提交
			  form.on('submit(demo1)', function(data){
				  let paramsObj = {
					  id : user.id,
					  password : data.field.password
				  }
				  
				  $.ajax({
					  url : 'http://localhost:8080/user/updatePass',
					  type : 'post',
					  data : paramsObj,
					  dataType : 'json',
					  success : (res) => {
						  if(res.code === 200){
							  layer.msg(res.msg);
							  localStorage.removeItem('loginUser');
							  parent.location.href = "login.html";
						  }else{
							  layer.msg(res.msg);
						  }
					  },
					  error: (error) => {
						  console.log(error);
					  }
				  })
				return false;
			  });
			  
			});
		</script>
	</body>
</html>
